package com.huawei.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;

/**
 * 鸿蒙版本处理工具类
 *
 * @since 2025-09-08
 */
public class HarmonyVersionUtil {
    private static final Logger log = LoggerFactory.getLogger(HarmonyVersionUtil.class);

    /**
     * 鸿蒙版本json文件名
     */
    public static final String HARMONY_VERSION_JSON = "harmony_version.json";

    /**
     * 项目中版本配置文件名
     */
    public static final String BUILD_PROFILE_JSON = "build-profile.json5";

    /**
     * 排序后的版本数组
     */
    private static String[] versions = new String[] {};

    static {
        // 初始化获取配置的版本
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            InputStream inputStream = HarmonyVersionUtil.class.getClassLoader()
                .getResourceAsStream(HARMONY_VERSION_JSON);
            if (inputStream != null) {
                versions = objectMapper.readValue(inputStream, String[].class);
                // 排序：降序
                Arrays.sort(versions, Collections.reverseOrder());
            } else {
                log.warn("can't find file of harmony_version.json");
            }
        } catch (Exception e) {
            log.error("loading file of harmony_version.json error: {}", e.getMessage());
        }
    }

    /**
     * 获取配置form版本集合
     *
     * @return 版本集合
     */
    public static String[] getVersions() {
        return versions;
    }

    /**
     * 获取文件build-profile.json5中的版本号，并与版本集合中匹配，匹配即为默认选择的版本号
     *
     * @param basePath 项目路径
     * @return 默认选中的form版本
     */
    public static String getSelectFromVersion(String basePath) {
        // 从项目的build-profile.json5中获取版本
        String versionFromProfile = getVersionFromProfile(basePath);
        if (StringUtils.isBlank(versionFromProfile)) {
            log.error("can't get version from file of build-profile.json5");
            return StringUtils.EMPTY;
        }

        for (String formVersion : versions) {
            if (formVersion.startsWith(versionFromProfile)) {
                return formVersion;
            }
        }
        log.warn("version {} don't match any version from config.", versionFromProfile);
        return StringUtils.EMPTY;
    }

    private static String getVersionFromProfile(String basePath) {
        if (StringUtils.isBlank(basePath)) {
            log.error("don't get base path of project.");
            return StringUtils.EMPTY;
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(new File(basePath + File.separator + BUILD_PROFILE_JSON));

            JsonNode compatibleSdkVersionNode = rootNode.path("app")
                .path("products")
                .get(0)
                .path("compatibleSdkVersion");

            if (!compatibleSdkVersionNode.isMissingNode()) {
                return compatibleSdkVersionNode.asText();
            }

        } catch (IOException e) {
            log.error("get version error form file of build-profile.json5. {}", e.getMessage());
        }
        return StringUtils.EMPTY;
    }
}
